package com.basic.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @Author: wisdom
 * @Date: 2024/4/1  8:11 PM
 * @Description:
 */
public class Client {

    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));

        //此处注册是为了接受服务端的消息
        channel.configureBlocking(false);
        Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_READ);

        //读消息
        new Thread(){
            @Override
            public void run() {
                //循环接受消息
                while (true) {
                    try {
                        readMsg(selector);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();


        Scanner scanner = new Scanner(System.in);
        System.out.println("请说：");
        while (true){
            String msg = scanner.next();
            channel.write(ByteBuffer.wrap(msg.getBytes()));
        }
    }

    /**
     * 读消息
     * @param selector
     */
    private static void readMsg(Selector selector) throws IOException {
        // keys和selectedKeys区别
        if(selector.select() > 0){
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isReadable()){
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    //把读到的缓冲区的数据转成字符串
                    String msg = new String(buffer.array());
                    System.out.println("收到其他客户端消息："+msg.trim());
                }
                iterator.remove();
            }
        }
    }
}
